<template>
    <div class="container">
        <div class="box">
            <p class="title">系统登录</p>
            <!-- 修正 model 绑定 -->
            <el-form :model="formData" :rules="rules" ref="formRef">
                <el-form-item label="" prop="account">
                    <el-input v-model="formData.account" prefix-icon="UserFilled" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item label="" prop="password">
                    <el-input v-model="formData.password" show-password prefix-icon="Lock" placeholder="请输入密码" />
                </el-form-item>
                <el-form-item>
                    <!-- 使用更具体的选择器 -->
                    <el-button class="login-button" type="primary" @click="login">登录</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { FormRules, FormInstance } from 'element-plus';
import { checklogin } from '../../api/account';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();

const formData = reactive({
  account: '',
  password: ''
})

const formRef = ref<FormInstance | null>(null);

const login = async () => {
     const { code, msg,token,id } = await checklogin(formData);
     console.log(token,id);
     sessionStorage.setItem('password', formData.password);
     sessionStorage.setItem('token',token);
     sessionStorage.setItem('accountid', id);
    if (code === 0) {
        console.log(msg);
      ElMessage.success(msg);      
      // 可以考虑使用命名路由
      router.push('/main'); 
    } else {
      ElMessage.error(msg);
    }
}

   
    


const validateAccount = (rule: any, value: string, callback: (error?: Error) => void) => {
  const reg = /^([a-z0-9]){4,11}$/;
  if (reg.test(value)) {
    callback();
  } else {
    callback(new Error('请输入正确的账号'));
  }
}

const validatePassword = (rule: any, value: string, callback: (error?: Error) => void) => {
  const reg = /^([a-z0-9]){4,11}$/;
  if (reg.test(value)) {
    callback();
  } else {
    callback(new Error('请输入正确的密码'));
  }
}

const rules = reactive<FormRules>({
  account: [
    { validator: validateAccount, trigger: 'blur' }
  ],
  password: [
    { validator: validatePassword, trigger: 'blur' }
  ]
})
</script>
<style scoped lang="scss">
.container {
    width: 100%;
    height: 100vh;
    background-size: cover;
    background-color: #304156;
}

.title {
    color: white;
    font-size: 30px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 40px;
}


:deep(.el-input__wrapper) {
    color: white;
    background-color: #29374b;
    border-radius: 5px;
    margin-top: 40px;
}

button {
    margin-top: 40px;
    width: 405px;
    height: 35px;
    color: white;
    background-color: #409EFF;
    border-radius: 5px;
    cursor: pointer;
}

.box {
    width: 400px;
    height: 400px;
    margin: auto;
}
</style>    